<?php

namespace App\Jobs;

use App\Models\Config;
use App\Models\Order;
use App\Models\User;
use App\Repositories\AmountRepo;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class RetailJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected  $order = null;
    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct(Order $order)
    {
        //
        $this->order = $order;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        if($this->order->distributed == 1) {
            return;
        }
        //1.获取到当前用户
        $buyer = User::where('id',$this->order->user_id)->first();
        if(!$buyer) {
            return;
        }
        //2.计算佣金
        $total = $this->order->total;
        $broker_scale = Config::where('name','broker_scale')->value('value');
        Log::info("分销金额:".$total."分销比例：".$broker_scale);
        $brokerage = $total * $broker_scale;
        //3.获取用户上级
        $parent = User::where('id',$buyer->pid)->first();
        if(!$parent) {
            Log::info("上级不存在");
            return;
        }
        //3.将佣金写入数据库并添加到用户的佣金字段
        DB::beginTransaction();
        try{
            $parent->brokerage = floatval($parent->brokerage) + $brokerage;
            $parent->save();
            //增加佣金记录
            AmountRepo::genneral($parent,'brokerage',$brokerage);
            //订单设置已分销
            $this->order->distributed = 1;
            $this->order->save();
            DB::commit();
        }catch (\Exception $e) {
            Log::info("分佣出错".$e->getMessage());
            DB::rollBack();
        }
        Log::info("用户".$parent->user_name."分佣结束.获得佣金：".$brokerage);
    }
}
